package com.xcl.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "xcl";

    //生成Token
    //claims：荷载数据
    public static String genToken(Map<String, Object> claims) {

        return JWT.create()
                .withClaim("claims",claims)  //设置荷载的数据
                .withExpiresAt(new Date(System.currentTimeMillis() + 4*60*60*1000)) //Token过期时间
                .sign(Algorithm.HMAC256(KEY));
    }


    //验证Token
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims").asMap();
    }

    public static void main(String[] args) {
        //构建业务数据
//        Map<String, Object> claims = new HashMap<>();
//        claims.put("userId", 1);
//        claims.put("userName", "Jack");
//
//        String token = genToken(claims);
//
//        System.out.println(token);

        try{
            String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsidXNlck5hbWUiOiJKYWNrIiwidXNlcklkIjoxfSwiZXhwIjoxNzQ0ODczOTQxfQ.XBDURKtyCNZp4QaeCxqu5hi-DZBLLJs7VSn4iHgFrDM";
            Map<String,Object> map = parseToken(token);
            System.out.println(map.get("userName"));
        }catch (Exception e){
            System.out.println("无效令牌");
            e.printStackTrace();

        }



    }



}
